<template>
  <div class="user-management">
    <!-- 顶部操作按钮区 -->
    <el-card style="height:620px">
      <div class="header">
        <el-button-group class="operation-buttons">
          <el-button @click="openAddRoleDialog">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
          <!-- 保留导入/导出按钮 -->
          <el-button>
            <el-icon><Download /></el-icon>
            导入
          </el-button>
          <el-button>
            <el-icon><Upload /></el-icon>
            导出
          </el-button>
        </el-button-group>

        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
              placeholder="请输入搜索内容"
              v-model="searchText"
              @keyup.enter.native="handleSearch"
          >
            <template #suffix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button
              type="primary"
              @click="handleSearch"
              class="search-button"
          >
            搜索
          </el-button>
        </div>
      </div>

      <!-- 用户表格 -->
      <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%; margin-top: 20px"
          max-height="calc(100vh - 180px)"
      >
        <el-table-column
            prop="index"
            label="序号"
            width="200"
        ></el-table-column>
        <el-table-column
            prop="id"
            label="ID"
            width="200"
        ></el-table-column>
        <el-table-column
            prop="nickname"
            label="角色昵称"
            min-width="150"
        ></el-table-column>
        <el-table-column
            prop="updateTime"
            label="更新时间"
            width="460"
        ></el-table-column>
        <el-table-column
            label="操作"
            width="220px"
            fixed="right"
        >
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination">
        <span>共 {{total}} 条</span>
        <span> </span>
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="10"
            :current-page="currentPage"
            :total="total"
            @current-change="handlePageChange"
        >
        </el-pagination>
      </div>

    </el-card>

    <!-- 添加角色弹窗 -->
    <el-dialog
        v-model="addRoleDialogVisible"
        title="新增角色"
        width="500px"
        @close="handleRoleDialogClose"
    >
      <el-form
          ref="addRoleFormRef"
          :model="addRoleForm"
          :rules="addRoleFormRules"
          label-width="80px"
          class="dialog-form"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
              v-model="addRoleForm.roleName"
              autocomplete="off"
              placeholder="请输入角色名称（如：管理员）"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
              v-model="addRoleForm.roleDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入角色描述（可选）"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addRoleForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Download, Upload, Search, Edit, Delete } from '@element-plus/icons-vue';
import {getRoleList, updateRole, deleteRole, selectRoleList} from '@/api/Role.js'
export default {
  name: 'UserManagement',
  setup() {
    // 模拟数据
    const tableData = ref([
      {
        index: 1,
        id: 3,
        nickname: 'tettt',
        updateTime: '2025-03-08 11:47:54'
      },
      {
        index: 2,
        id: 4,
        nickname: 'tom',
        updateTime: '2025-04-15 11:02:20'
      }
    ]);


    // 搜索文本
    const searchText = ref('');

    // 分页相关
    const total = ref(2);
    const currentPage = ref(1);

    // 处理搜索
    const handleSearch = () => {
      console.log('搜索内容:', searchText.value);
      // 实际应用中这里会调用API获取搜索结果
    };

    // 处理编辑
    const handleEdit = (row) => {
      console.log('编辑用户:', row);
      // 实际应用中这里会跳转到编辑页面或打开编辑对话框
    };

    const getrole =async () => {
      const query = {
        pageNum: currentPage.value,
        pageSize: 10,
        name: searchText.value
      }
      const res = await getRoleList(query);
      tableData.value = res.data.list;
      console.log('111',tableData.value)
    }
    getrole()

    // 处理删除
    const handleDelete = (row) => {
      console.log('删除用户:', row);
      // 实际应用中这里会调用API删除用户并刷新列表
    };

    // 处理分页
    const handlePageChange = (page) => {
      currentPage.value = page;
      // 实际应用中这里会调用API获取对应页的数据
    };


    // 添加角色弹窗相关数据
    const addRoleDialogVisible = ref(false); // 弹窗显示状态
    const addRoleForm = ref({ // 表单数据模型
      roleName: '', // 角色名称（必填）
      roleDesc: '', // 角色描述（可选）
      status: '1' // 状态（默认启用）
    });

    // 表单验证规则
    const addRoleFormRules = reactive({
      roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度需在2-20个字符之间', trigger: 'blur' }
      ]
    });

    // 表单引用
    const addRoleFormRef = ref(null);

    // 打开添加角色弹窗
    const openAddRoleDialog = () => {
      addRoleDialogVisible.value = true;
      resetRoleForm(); // 打开弹窗时重置表单
    };

    // 重置表单数据
    const resetRoleForm = () => {
      addRoleForm.value = {
        roleName: '',
        roleDesc: '',
        status: '1'
      };
    };


    // 关闭弹窗时重置表单
    const handleRoleDialogClose = () => {
      resetRoleForm(); // 清空表单数据
      addRoleFormRef.value?.resetFields(); // 清除验证状态
    };

    // 处理角色添加
    const handleAddRole = async () => {
      // 触发表单验证
      await addRoleFormRef.value?.validate(valid => {
        if (!valid) return; // 验证不通过则返回

        // 模拟新增角色逻辑（实际需调用API）
        const newRole = {
          id: Date.now(), // 实际应使用服务端生成的ID
          index: tableData.value.length + 1, // 序号自动递增
          nickname: addRoleForm.value.roleName, // 角色昵称（表格显示字段）
          roleName: addRoleForm.value.roleName, // 角色名称（存储字段）
          roleDesc: addRoleForm.value.roleDesc, // 角色描述
          status: addRoleForm.value.status === '1' ? '启用' : '禁用', // 状态文本
          updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ') // 当前时间
        };

        // 添加到表格数据
        tableData.value.push(newRole);
        total.value = tableData.value.length; // 更新总数

        // 关闭弹窗并提示用户
        addRoleDialogVisible.value = false;
        ElMessage.success('角色添加成功');
      });
    };

    return {
      // 原有返回值
      tableData,
      searchText,
      total,
      currentPage,
      handleSearch,
      handleEdit,
      handleDelete,
      handlePageChange,
      Plus,
      Download,
      Upload,
      Search,
      Edit,
      Delete,

      // 新增返回值（添加角色功能）
      addRoleDialogVisible,
      addRoleForm,
      addRoleFormRules,
      addRoleFormRef,
      openAddRoleDialog,
      handleRoleDialogClose,
      handleAddRole
    };
  }
};
</script>

<style scoped>
/* 保留原有样式，新增弹窗样式 */
.dialog-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-radio-group {
  display: flex;
  gap: 10px;
}

.el-input {
  width: 100%;
}

.el-input__textarea {
  min-height: 80px;
}

.user-management {
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
}

.operation-buttons button {
  margin-right: 10px;
  width: 100px;
  font-size: 14px;
}

.search-container {
  display: flex;
  align-items: center;
  width: 320px;
}

.search-container .el-input {
  flex: 1;
  margin-right: 10px;
}

/* 使用深度选择器确保样式生效 */
::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center;
  vertical-align: middle;
  padding: 10px 0;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

.el-button--primary {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #d9ecff;
  padding: 6px 12px;
  font-size: 12px;
}

.el-button--danger {
  color: #fff;
  background-color: #f56c6c;
  border-color: #f56c6c;
  padding: 6px 12px;
  font-size: 12px;
}

.edit-button {
  color: #409eff;
  background-color: transparent;
  border-color: transparent;
}

.delete-button {
  color: #f56c6c;
  background-color: transparent;
  border-color: transparent;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
}

.pagination span {
  margin-right: 10px;
  color: #666;
}

.el-pagination {
  margin-top: 0;
}
</style>
